package com.nowcoder.community.scheduler;


import com.nowcoder.community.property.WkProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

@Slf4j
@Component
public class ShareImageCleaner {

    @Autowired
    private WkProperty wkProperty;

    /***
     * 每 10 秒清理一次长图
     * */
    @Scheduled(fixedRate = 10*1000)
    public void cleanTempImage() throws IOException {
        log.info("开始清理长图");
        try (Stream<Path> list = Files.list(Paths.get(wkProperty.getStorage()))) {
            list.forEach(path -> {
                if (path.getFileName().toString().endsWith("_ok")){
                    try {
                        Files.delete(path);
                        log.info("删除临时文件：" + path);
                    } catch (IOException e) {
                        log.error("删除临时文件失败：" + e.getMessage());
                    }
                }
            });
        }
    }
}
